<style lang="less">
textarea.ivu-input {
  max-width: 100%;
  height: auto;
  min-height: 32px;
  vertical-align: bottom;
  font-size: 12px;
}
  .colDiv14{
    text-align: center;
  }

  .mapClass{
    position: absolute;
    right: 0px;
    bottom: 10px;
    width: 45%;
    height: 50%;
  }
</style>
<template>
  <div class="search">
    <Row>
      <Col >
        <Card>
          <p slot="title">
            <span v-if="type==0">新增事件</span>
            <span v-else-if="type==1">编辑事件</span>
            <span v-else>查看事件详情</span>
          </p>
          <div class="search1">
            <Form
                    ref="form"
                    :model="form"
                    :label-width="95"
                    :rules="formValidate"
                    style="position:relative"
            >
              <Row>
                <Col span="13">
              <FormItem label="申请人" prop="title" v-if="type!=0&&type!=1">{{form.createBy}}</FormItem>
              <FormItem label="事件编码">{{form.eventNum}}</FormItem>

              <FormItem label="事件类型" prop="type">
                <Select v-model="form.eventType" placeholder="请选择" style="width: 200px">
                  <Option
                          v-for="(item, i) in dictType"
                          :key="i"
                          :value="item.value"
                  >{{item.title}}</Option>
                </Select>
              </FormItem>

                <!--事件详情显示-->
               <FormItem label="事件来源" prop="type" v-show="form.type!=0">
                <Select v-model="form.eventSource" placeholder="请选择" style="width: 200px">
                  <Option
                          v-for="(item, i) in eventSourceType"
                          :key="i"
                          :value="item.value"
                  >{{item.title}}</Option>
                </Select>
              </FormItem>

              <FormItem label="事件描述" prop="eventDescribe">
                <Input
                        type="textarea"
                        v-model="form.eventDescribe"
                        :rows="5"
                        placeholder="请输入详细情况"
                        style="width: 550px"
                />
              </FormItem>

              <FormItem label="发生地点" prop="locality">
                <Input v-model="form.locality" style="width:550px"/>
              </FormItem>

                  <div v-if="taskDate">
                    <FormItem label="任务期限" prop="taskEndTime" >
                      <DatePicker type="datetime" :options="options3" @on-change="selectDateRange" v-model="form.taskEndTime" placeholder="请选择" clearable style="width: 200px"></DatePicker>
                    </FormItem>
                    <FormItem label="任务时长" prop="taskTime">
                      <span :style="taskTime == '已过期'?'color: red':'color: green'" v-if="">{{taskTime}}</span>
                    </FormItem>
                  </div>


                <!--事件详情显示-->
               <FormItem label="联系电话" prop="phone" v-show="form.type!=0">
                <Input v-model="form.phone" style="width:550px"/>
              </FormItem>

                <FormItem label="图片上传"  v-show="form.type==0">
                  <uploadPicThumb :limit="3" @on-change="form.front=$event" ref="uploadPicThumb"></uploadPicThumb>
                </FormItem>

              <FormItem label="选择部门" prop="departs" :error="error" v-if="printDeparts">
                <Select
                        style="width: 200px"
                        v-model="form.departs"
                        placeholder="请选择或输入搜索"
                        filterable
                        clearable
                        :loading="userLoading"
                        @on-change="handleSelectDepTree"
                >
                  <Option v-for="(item, i) in departments" :key="i" :value="item.id">{{item.title}}</Option>
                </Select>
              </FormItem>
              <Form-item class="br">
                <Button
                        type="primary"
                        :loading="submitLoading"
                        @click="handelSubmit"
                        v-if="type==0||type==1"
                >保存并关闭</Button>
                <Button @click="handelCancel">关闭</Button>
              </Form-item>
              </Col>
                <Col span="11">
                <div class="colDiv14" v-show="printFront">
                  <h2>事件上传图片</h2>
                  <FormItem label="">
                    <UploadPicThumb  @on-change="form.front=$event"  ref="uploadThumb1"></UploadPicThumb>
                  </FormItem>
                </div>
                  <div class="colDiv14"  v-show="printLater">
                    <h2>事件结束图片</h2 >
                    <FormItem label="">
                      <UploadPicThumb   @on-change="form.later=$event"  ref="uploadThumb2"></UploadPicThumb>
                    </FormItem>
                  </div>
                </Col>
                <div id="eventReportMap" class="mapClass" v-show="mapFlag"></div>
          </Row>
              <Spin size="large" fix v-if="loading"></Spin>
            </Form>

          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>

<script>
import {
  getEventReport,
  addEventReport,
  updateEventReport,
  applyLeave,
  getdeps
} from "@/api/activiti";
import util from "@/libs/util";
import MapLoader from '@/plugins/amap.js';
import printJS from "print-js";
import UploadPicThumb from "./upload-pic-thumb.vue";
import uploadPicThumb from "../../my-components/xboot/upload-pic-thumb";
export default {
  name: "leave-notcache",
  components: {
      uploadPicThumb,
      UploadPicThumb
    },
  data() {
    return {
      options3: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now();
        }
      },
      taskTime:"",
      departments:[], //部门
      type: 0,
      loading: false, // 表单加载状态
      modalVisible: false,
      dictType: this.$store.state.dict.eventType,
      eventSourceType: this.$store.state.dict.eventSource,
      form: {
        // 添加或编辑表单对象初始化数据
        type: 0,
        eventNum: "",
        eventSource: "电话投诉",
        eventType:"",
          front:[],
          later: [],
        eventDescribe: "",
        locality: "",
        phone: "",
        fileId: "",
          departs:""
      },
      formValidate: {
        // 表单验证规则
        locality: [{ required: true, message: "地点不能为空", trigger: "blur" }],
        phone: [{ required: false, message: "号码不能为空", trigger: "blur" }],
        eventDescribe: [{ required: true, message: "原因不能为空", trigger: "blur" }],
        departs: [{ required: true , message: "选择部门不能为空", trigger: "blur" }],
      },
        printLater: false,  // 办结图片显示
        mapFlag: false,  // 地图标点显示
        printFront: false,  //事件上传图片
        taskDate:false,//任务完成期限
        printDeparts: false, //选择部门显示
      submitLoading: false, // 添加或编辑提交状态

      processList: [],
      backRoute: "",
      procDefId: "",
        rowDemo:0.5,
    };
  },
  methods: {
    init() {
      this.getdep();
      let timestamp = this.generateTimeReqestNumber();
      this.form.eventNum = timestamp;
      this.type = this.$route.query.type;
      this.backRoute = this.$route.query.backRoute;
      this.procDefId = this.$route.query.procDefId;
      //镇河长工作流程选择部门显示
      let str =  this.procDefId;
      let _procDefId = new Array();
      if(str != undefined){
        _procDefId = str.split(":");
      }
      if(_procDefId[0] == "镇河长工作流程"){
        this.printDeparts = true;
      }
      if(_procDefId[0] != "村河长工作流程"){
        this.taskDate = true;
      }
      let flag = this.$route.query.mapFlag;
      if(1 == flag){
        this.mapFlag = true;
        this.getMap();
      }

      if (this.type != 0) {
        this.form.id = this.$route.query.id;
        this.getData();
      } else {
        this.$refs.form.resetFields();
      }
    },
    selectDateRange(v) {
      this.form.taskEndTime = v;
      this.taskTime = "";
      if("" != v){
        let endDate = new Date(v);
        let nowDate = new Date();
        if (endDate.getTime()<nowDate.getTime()) {
          this.$Message['warning']({
            background: true,
            content: '所选时间不能小于当前时间!'
          });
          this.form.taskEndTime = "";
          this.taskTime = "";
        }else{
          this.taskTime = util.millsToTime(endDate.getTime()-nowDate.getTime());
        }
      }
    },
    getMap(){
      let that = this;
      MapLoader().then(AMap => {
        that.map =new AMap.Map("eventReportMap", {
          zoom:11,
          zooms:[11,15],
          center:[116.70,40.16],
          pitch: 0,
          viewMode: '3D',
          resizeEnable: true,
        });
      }, e => {
        console.log('地图加载失败' ,e)
      })
    },
    getdep() {
      getdeps().then(res => {
        if (res.success) {
          this.departments = res.result.departments;
        }
      });
    },
    getData() {
      this.loading = true;
      let that = this;
      getEventReport(this.form.id).then(res => {
        this.loading = false;
        if (res.success) {
          // 转换null为""
          let v = res.result;
          for (let attr in v) {
            if (v[attr] == null) {
              v[attr] = "";
            }
          }
          let str = JSON.stringify(v);
          let data = JSON.parse(str);
          this.form = data;

          if("" != data.taskEndTime){
            let endDate = new Date(data.taskEndTime);
            let nowDate = new Date();
            if (endDate.getTime()<nowDate.getTime()) {
              this.taskTime = "已过期";
            }else{
              this.taskTime = util.millsToTime(endDate.getTime()-nowDate.getTime());
            }
          }

          let lat = this.form.lat;
          let lng = this.form.lng;
          if(this.mapFlag && lat != "undefined" && lat !="" && lng != "undefined" && lng !=""){
            this.addMapPoint(lng,lat);
          }

            this.printFront = false;
            if(data.front != null && data.front != ""){
                this.printFront = true;
                var _later = data.front;
                var str2 = new Array();
                str2 = _later.split(",");
                this.$refs.uploadThumb1.setData(str2);
            }
          if(data.later != null && data.later != ""){
              this.printLater = true;
              var _later = data.later;
              var str2 = new Array();
              str2 = _later.split(",");
              this.$refs.uploadThumb2.setData(str2);
          }
          //选择部门显示或隐藏
            if(data.departs != null&&data.departs != ""){
                this.printDeparts = true;
            }
        }
      });
    },
    addMapPoint(lng,lat){
      let markers = this.map.getAllOverlays('marker')
      this.map.remove(markers);

      var marker = new AMap.Marker({
        position: [lng,lat]
      });
      this.map.add(marker);
      this.map.setFitView();
    },
    handelSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          if (this.type == 0) {
            // 添加 避免编辑后传入id等数据 记得删除
            delete this.form.id;
            this.form.procDefId = this.procDefId;
            addEventReport(this.form).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.closeCurrentPage();
              }
            });
          } else if (this.type == 1) {
            let form = this.form;
            delete form.applyTime;
            // 编辑
            updateEventReport(form).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.closeCurrentPage();
              }
            });
          }
        }
      });
    },
    handelCancel() {
      this.closeCurrentPage();
    },
    // 关闭当前页面
    closeCurrentPage() {
      this.$store.commit("removeTag", "leave");
      localStorage.pageOpenedList = JSON.stringify(
        this.$store.state.app.pageOpenedList
      );
      this.$router.push({
        name: this.backRoute
      });
    },
    generateTimeReqestNumber() {
    var date = new Date();
    return date.getFullYear().toString() + this.pad2(date.getMonth() + 1) + this.pad2(date.getDate()) + this.pad2(date.getHours()) + this.pad2(date.getMinutes()) + this.pad2(date.getSeconds());
    },
    pad2(n) {
        return n < 10 ? '0' + n : n
    }
  },
  mounted() {
    this.init();
  },
  watch: {
    // 监听路由变化
    $route(to, from) {
      if (to.name == "event-report") {
        this.getDictData();
        this.type = this.$route.query.type;
        this.backRoute = this.$route.query.backRoute;
        this.procDefId = this.$route.query.procDefId;
        if (this.type != 0) {
          this.form.id = this.$route.query.id;
          this.getData();
        } else {
          this.$refs.form.resetFields();
        }
      }
    }
  }
};
</script>